package com.qfedu.dao.impl;

import com.qfedu.dao.GoodsDao;
import com.qfedu.pojo.Goods;
import com.qfedu.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 创建者: QF-SUN
 * 创建时间: 2023/4/4 10:56
 * 描述:
 */
public class GoodsDaoImpl implements GoodsDao {

    QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());

    @Override
    public List<Goods> findListByTypeId(int startIndex,int  pageSize,String  typeId) {
        String sql = "SELECT * FROM tb_goods where typeid = ? limit ?, ?";
        try {
            return  qr.query(sql, new BeanListHandler<>(Goods.class), typeId, startIndex, pageSize);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long findTotalCount(String typeId) {
        String sql = "SELECT count(0) FROM tb_goods where typeid = ?";
        try {
            long count = (long) qr.query(sql, new ScalarHandler(), typeId);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Goods findById(int goodsId) {
        String sql = "SELECT * FROM tb_goods where id = ?";
        try {
            return qr.query(sql, new BeanHandler<>(Goods.class), goodsId);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询商品详情失败");
        }
        return null;
    }
}
